package code.jzh.compiler.scanner;

import code.jzh.compiler.util.Constants;

public class Lexeme {
	public int type;
	public String literal;
	public String typeStr;
	public String convertLiteral;
	
	public Lexeme(int type, String literal, String typeStr) throws Exception {
		this.type = type;
		this.literal = literal;
		convertLiteral = literal;
		convertLiteral = convertStringLiteral(type, convertLiteral);
		this.typeStr = typeStr;
	}
	
	public String convertStringLiteral(int type, String str) throws Exception {
		if(type==LexerType.STRING.ordinal()) {
			str = str.substring(1);
			str = str.substring(0, str.length()-1);
			StringBuilder sb = new StringBuilder();
			for(int i=0; i<str.length(); i++) {
				char c = str.charAt(i);
				if(c==Constants.escape) {
					i++;
					char next = str.charAt(i);
					if(next==Constants.escape) {
						sb.append(Constants.escape);
					}else if(next=='n') {
						sb.append('\n');
					}else if(next=='t') {
						sb.append('\t');
					}else if(next=='"') {
						sb.append('"');
					}else {
						throw new Exception("input error: "+Constants.escape+next+" is illegal");
					}
				}else {
					sb.append(c);
				}
			}
			return sb.toString();
		}
		return str;
	}
	
	public void printLexeme() {
		System.out.println(typeStr+"["+convertLiteral+"]");
	}
}
